package common.controller;

import common.entity.User;
import common.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/{url}")
    public String redirect(@PathVariable("url")String url){
        return url;
    }
    @PostMapping("/login")
    public String login(String id, String password, Model model) {
        Subject subject = SecurityUtils.getSubject();
        User us = userService.findById((id));
        if (us != null) {
            String salt = us.getSalt();
            password = new SimpleHash("md5", password, salt, 2).toString();
        }
        UsernamePasswordToken token = new UsernamePasswordToken(id, password);
        try {
            subject.login(token);
            User user = (User) subject.getPrincipal();
            subject.getSession().setAttribute("user", user);
            return "index";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            model.addAttribute("msg", "用户名不存在");
            return "login";
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            model.addAttribute("msg", "密码有误");
            return "login";
        }
    }

    @ResponseBody
    @GetMapping("/unauthor")
    public String unauthor(){
        public String unauthor(){
            return "没有权限，无法访问";
        }
        @GetMapping("/logout")
        public String logout(){
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            return "login";
        }

        @PostMapping("/register")
                public String register(Id id,Model model){
            String id = id.getId();
            String password = user.getPassword();
            if(id==null||id==""){
                model.addAttribute("msg", "用户名不能为空");
                return "register";
            }else if(password==null||password=="") {
                model.addAttribute("msg", "密码不能为空");
                return "register";
            }else if(userService.findById(id)!=null) {
                model.addAttribute("msg", "用户名已被占用");
                return "register";
            }else {
                userService.createUser(user);
                return "login";
            }
        }
    }
}
